//
//  AFNController.m
//  OCDemo
//
//  Created by BH on 15/11/30.
//  Copyright © 2015年 baohan. All rights reserved.
//

#import "AFNController.h"
#import "KSNetRequest.h"
#import "KSCache.h"
#import "GlobalDefine.h"

#define Image_Name @"image"

@interface AFNController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate>
{
    NSMutableArray *imgPathArr;
    NSMutableArray *imgArr;
}

@property(nonatomic,strong)UIButton *sender;

@end

@implementation AFNController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    imgArr = [NSMutableArray array];
    imgPathArr = [NSMutableArray array];
}

//断网状态下必写
-(void)reloadRequest
{
    [self post:self.sender];
}

//GET
- (IBAction)get:(id)sender {
    self.sender = sender;
    
    /*----------带缓存------------
    [KSNetRequest requestTarget:self method:@"GET" url:@"http://192.168.2.13:8008/Property/GetDistrictName" parameters:nil success:^(NSURLSessionDataTask * _Nullable task, id  _Nullable responseObject) {
        NSLog(@"%@",responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
        NSLog(@"%@",error.localizedDescription);
    }];*/
    
    //----------不带缓存----------//
    [KSNetRequest requestProgress:@"GET" url:@"http://192.168.2.13:8008/Property/GetDistrictName" parameters:nil success:^(NSURLSessionDataTask * _Nullable task, id  _Nullable responseObject) {
        NSLog(@"%@",responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
        NSLog(@"%@",error.localizedDescription);
    }];
}

//POST
- (IBAction)post:(id)sender {
    self.sender = sender;
    
    NSMutableDictionary* dic = [NSMutableDictionary new];
    
    [dic setObject:@"1.0" forKey:@"appVersion"];
    
    /*--------------带缓存--------------
    [KSNetRequest requestTarget:self method:@"POST" url:@"http://123.57.176.88:8090/hunparapp/sysNew/getSysNewList" parameters:dic success:^(NSURLSessionDataTask * _Nullable task, id  _Nullable responseObject) {
        
        NSLog(@"%@",responseObject);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
        NSLog(@"%@",error.localizedDescription);
    }];*/
    
    //------------不带缓存---------------//
    [KSNetRequest requestProgress:@"POST" url:@"http://123.57.176.88:8090/hunparapp/sysNew/getSysNewList" parameters:dic success:^(NSURLSessionDataTask * _Nullable task, id  _Nullable responseObject) {
        NSLog(@"%@",responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
        NSLog(@"%@",error.localizedDescription);
    }];
}

//上传图片
- (IBAction)picture:(id)sender {
    
    self.sender = sender;
    
    UIAlertController *sheet = [UIAlertController alertControllerWithTitle:@"选择图片" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    [sheet addAction:[UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        //从相机获取
        [self pickImageFromAlbumOrCamera:YES];
    }]];
    
    [sheet addAction:[UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        //从相册获取
        [self pickImageFromAlbumOrCamera:NO];
    }]];
    
    [sheet addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        [sheet dismissViewControllerAnimated:YES completion:nil];
    }]];
    
    [self presentViewController:sheet animated:YES completion:nil];
    
}

//清空缓存
- (IBAction)cleanCache:(id)sender {
    
    BOOL ret = [KSCache cleanCache];
    
    if (ret) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"清空完成" message:nil preferredStyle:UIAlertControllerStyleAlert];
        [self presentViewController:alert animated:YES completion:^{
            [alert dismissViewControllerAnimated:YES completion:nil];
        }];
    }
}

//获取图片
-(void)pickImageFromAlbumOrCamera:(BOOL)flag
{
    UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
    imagePicker.delegate = self;
    
    if (flag) {
        imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
    }else{
        imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    }
    imagePicker.allowsEditing = YES;
    imagePicker.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
    
    [self presentViewController:imagePicker animated:YES completion:nil];
}

//压缩图片
- (UIImage *)scaleToSize:(UIImage *)img size:(CGSize)size{
    // 创建一个bitmap的context,并把它设置成为当前正在使用的context
    UIGraphicsBeginImageContext(size);
    // 绘制改变大小的图片
    [img drawInRect:CGRectMake(0,0, size.width, size.height)];
    // 从当前context中创建一个改变大小后的图片
    UIImage* scaledImage =UIGraphicsGetImageFromCurrentImageContext();
    // 使当前的context出堆栈
    UIGraphicsEndImageContext();
    //返回新的改变大小后的图片
    return scaledImage;
}

//保存图片到document
- (void)saveImage:(UIImage *)tempImage WithName:(NSString *)imageName
{
    NSData* imageData = UIImagePNGRepresentation(tempImage);
    
    NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString* documentsDirectory = [paths objectAtIndex:0];
    NSString* fullPathToFile = [documentsDirectory stringByAppendingPathComponent:imageName];
    
    [imageData writeToFile:fullPathToFile atomically:NO];
}

-(void)uploadImage
{
    //像字典添加除图片之外的相关参数
    NSMutableDictionary* dic = [NSMutableDictionary new];
    [dic setObject:@"1.0" forKey:@"appVersion"];
    
    //要上传的服务器地址
    NSString *url = [NSString stringWithFormat:@"%@ShopManage-addStore",DOMAIN_PATH];
    NSLog(@"有图片上传");
    
    [KSNetRequest postRequestWithURL:url postParems:dic picFilePath:imgPathArr picFileName:imgArr];
    
}

#pragma mark - UIImagePickerController delegate
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    UIImage *originalImage = [info valueForKey:UIImagePickerControllerEditedImage] ;
    
    NSData *imageData = UIImageJPEGRepresentation([self scaleToSize:originalImage size:CGSizeMake(120.0, 120.0)], 0.5);
    // 得到图片的缓存数据
    static int index = 1;
    NSString * newImageName = [NSString stringWithFormat:@"%@%zi%@", Image_Name, index, @".jpg"];
    NSString  *jpgPath = NSHomeDirectory();
    jpgPath = [jpgPath stringByAppendingPathComponent:@"Documents"];
    jpgPath = [jpgPath stringByAppendingPathComponent:newImageName];
    [imageData writeToFile:jpgPath atomically:YES];
 
    [imgArr addObject:imageData];
    
    index ++ ;
    
    [self uploadImage];
    
    [self dismissViewControllerAnimated:YES completion:nil];
}

-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

@end
